package k8s

import (
	coreClient "k8s.io/client-go/kubernetes"
	restClient "k8s.io/client-go/rest"
	cmdClient "k8s.io/client-go/tools/clientcmd"
	metricsClient "k8s.io/metrics/pkg/client/clientset/versioned"
)

var (
	client *K8sClient
)

// default k8sclient
func Client() *K8sClient {
	if client == nil {
		k, err := defaultK8sClient()
		if err != nil {
			panic(err)
		}
		client = k
	}

	return client
}

func defaultK8sClient() (*K8sClient, error) {
	return NewK8sClientUseServiceAccount()
}

type K8sClient struct {
	Clientset        coreClient.Interface
	MetricsClientSet *metricsClient.Clientset
	RestConfig       *restClient.Config
}

func NewK8sClientUseServiceAccount() (*K8sClient, error) {
	restConfig, err := restClient.InClusterConfig()
	if err != nil {
		return nil, err
	}

	clientset, err := coreClient.NewForConfig(restConfig)
	if err != nil {
		return nil, err
	}

	// TODO if needed
	metricsClient, _ := metricsClient.NewForConfig(restConfig)

	return &K8sClient{
		Clientset:        clientset,
		MetricsClientSet: metricsClient,
		RestConfig:       restConfig,
	}, nil
}

func NewK8sClient(kubeconfigPath string) (*K8sClient, error) {
	restConfig, err := cmdClient.BuildConfigFromFlags("", kubeconfigPath)
	if err != nil {
		return nil, err
	}

	clientset, err := coreClient.NewForConfig(restConfig)
	if err != nil {
		return nil, err
	}

	// TODO if needed
	metricsClient, _ := metricsClient.NewForConfig(restConfig)

	return &K8sClient{
		Clientset:        clientset,
		MetricsClientSet: metricsClient,
		RestConfig:       restConfig,
	}, nil
}
